<template>
  <n-space v-if="!isLogin" style="margin-right: 40px;">
    <n-button @click="showLogin = true; loginForm.account = loginForm.password = '';">登录</n-button>
    <n-modal v-model:show="showLogin">
      <n-card style="width: 450px;" title="登录">
        <n-form :model="loginForm">
          <n-form-item label="学号">
            <n-input placeholder="请输入学号" type="text" v-model:value="loginForm.account" />
          </n-form-item>
          <n-form-item label="密码">
            <n-input placeholder="请输入密码" type="password" v-model:value="loginForm.password" />
          </n-form-item>
          <n-form-item>
            <n-button @click="login" secondary type="primary" attr-type="button">登录</n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>
    <n-button
      @click="showRegister = true; regForm.account = regForm.name = regForm.password = regForm.repassword = ''"
    >注册</n-button>
    <n-modal v-model:show="showRegister">
      <n-card style="width: 450px" title="注册">
        <n-form :model="regForm">
          <n-form-item label="姓名">
            <n-input placeholder="请输入姓名" v-model:value="regForm.name" />
          </n-form-item>
          <n-form-item label="学号">
            <n-input placeholder="请输入学号" v-model:value="regForm.account" />
          </n-form-item>
          <n-form-item label="密码">
            <n-input placeholder="请输入密码" v-model:value="regForm.password" type="password" />
          </n-form-item>
          <n-form-item label="再次输入密码">
            <n-input placeholder="请再次输入密码" v-model:value="regForm.repassword" type="password" />
          </n-form-item>
          <n-form-item label="性别">
            <n-radio-group v-model:value="regForm.sex">
              <n-radio-button value="1">男</n-radio-button>
              <n-radio-button value="0">女</n-radio-button>
            </n-radio-group>
          </n-form-item>
          <n-form-item>
            <n-button secondary type="primary" @click="register">注册</n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>
  </n-space>
  <n-space v-else style="margin-right: 10px;">
    <!-- 这里设置self自身的界面 使用modal实现 -->
    <n-dropdown trigger="hover" @select="handleSelect" :options="options">
      <n-button quaternary>你好，{{ user.name }}</n-button>
    </n-dropdown>
    <n-modal v-model:show="showInfo">
      <n-card style="width: 450px;" title="个人信息">
        <!-- 这里修改为点击左侧名称即可更改 -->
        <div class="rows">
          <div class="row">
            <n-button text @click="changeRow.changeName = !changeRow.changeName">姓名:</n-button>
            <n-space v-if="!changeRow.changeName">{{ user.name }}</n-space>
            <n-input
              v-else
              v-model:value="changeInfoForm.name"
              style="width: 300px;"
              placeholder="请输入姓名"
            >{{ user.name }}</n-input>
          </div>
          <div class="row">
            <n-space>学号:</n-space>
            <n-space>{{ user.account }}</n-space>
          </div>
          <div class="row">
            <n-button text @click="changeRow.changeSex = !changeRow.changeSex">性别:</n-button>
            <n-space v-if="!changeRow.changeSex">{{ user.sex }}</n-space>
            <n-space v-else>
              <n-radio-group v-model:value="changeInfoForm.sex">
                <n-radio-button value="1">男</n-radio-button>
                <n-radio-button value="0">女</n-radio-button>
              </n-radio-group>
            </n-space>
          </div>
          <div class="row">
            <n-button text @click="getClasses">班级:</n-button>
            <n-space vertical v-if="!changeRow.changeClasses">
              <n-space  v-for="_class in user.classes" :key="_class">
                {{ _class }}
              </n-space>
            </n-space>

            <n-select
              v-else
              v-model:value="changeInfoForm.classes"
              :options="classes.data"
              :multiple="classes.multiple"
              style="width: 300px;"
            ></n-select>
          </div>
        </div>
        <template #footer>
          <n-button
            type="primary"
            v-if="(changeRow.changeClasses || changeRow.changeName || changeRow.changePassword || changeRow.changeSex)"
            @click="updateUser"
          >完成</n-button>
          <n-space v-else>点击左侧标题即可修改信息</n-space>
        </template>
      </n-card>
    </n-modal>
  </n-space>
</template>

<style>
.rows {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

<script lang="ts">
import { defineComponent } from "@vue/runtime-core";
import { ref } from "@vue/reactivity";
import { useMessage, NForm, NFormItem, NSelect } from "naive-ui";
import { getSelf, toLogin, toRegister, updateUser, linkClass } from '@/utils/LoginReg';
import { getClasses } from "@/utils/classes";

const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;

export default defineComponent({
  components: { NForm, NFormItem, NSelect },
  created() {
    this.setSelfData()
  },
  setup() {
    const message = useMessage();
    const optionStudent = [
      {
        label: '个人信息',
        key: 'changeInfo'
      },
      {
        label: '退出登录',
        key: 'logout'
      }
    ];
    const optionTeacher = [
      {
        label: '个人信息',
        key: 'changeInfo'
      },
      {
        label: '题目管理',
        key: 'uploadQuestion'
      },
      {
        label: '竞赛管理',
        key: 'createContest'
      },
      {
        label: '退出登录',
        key: 'logout'
      }
    ];
    return {
      message,
      optionStudent,
      optionTeacher,
      options: ref(optionTeacher),
    };
  },
  data() {
    return {
      isLogin: ref(false),
      showLogin: ref(false),
      showRegister: ref(false),
      showInfo: ref(false),
      changeRow: ref({
        changeName: false,
        changePassword: false,
        changeSex: false,
        changeClasses: false
      }),
      classes: ref({
        data: [{ id: 0, label: '', value: '', disabled: false }],
        multiple: false,
        selectedValue: null
      }),
      loginForm: ref({
        account: '',
        password: ''
      }),
      regForm: ref({
        name: '',
        account: '',
        password: '',
        repassword: '',
        sex: 0
      }),
      user: ref({
        account: '',
        name: '',
        sex: '',
        classes: [''],
        role: ''
      }),
      changeInfoForm: ref({
        name: '',
        sex: 1,
        classes: ['']
      }),
    }
  },
  methods: {
    handleSelect(key: string) {
      if (key == 'logout') {
        this.message.info('已成功退出账号');
        this.isLogin = false;
        this.$router.push('/');
      } else if (key == 'changeInfo') {
        this.showInfo = true;
      } else if (key == 'uploadQuestion') {
        this.$router.push('/manage/question');
      } else if (key == 'createContest') {
        this.$router.push('/manage/contest');
      }
    },
    async login() {
      if (this.loginForm.account == '') {
        this.message.error('未输入学号');
      } else if (this.loginForm.password == '') {
        this.message.error('未输入密码');
      } else {
        let flag = await toLogin(this.loginForm.account, this.loginForm.password);
        if (flag == 0) {
          this.message.success('登陆成功');
          this.showLogin = false;
          await this.setSelfData();
        } else if (flag == 1) {
          this.message.error('账号或密码错误，登录失败');
        } else {
          this.message.error('服务器错误');
        }
      }
    },
    async register() {
      console.log(this.regForm);
      if (this.regForm.name == '') {
        this.message.error('未输入姓名');
      } else if (this.regForm.account == '') {
        this.message.error('未输入学号');
      } else if (!passwordRegex.test(this.regForm.password)) {
        this.message.error('请输入一串至少包含数字与字符的8位密码');
      } else if (this.regForm.password != this.regForm.repassword) {
        this.message.error('两次密码输入不一致，请重新检查');
      } else {
        if (await toRegister(this.regForm.name, this.regForm.account, this.regForm.password, this.regForm.sex)) {
          this.showRegister = false;
          this.message.success('注册成功');
        }
      }
    },
    async setSelfData() {
      const user = await getSelf();
      if (user) {
        this.user.name = user.name;
        this.user.account = user.number;
        this.user.role = user.role;
        this.user.classes = user.classes;
        this.user.sex = user.sex == 1 ? '男' : '女';
        this.$store.commit('setUser', this.user);
        this.isLogin = true;
        if (this.user.role == '学生') {
          this.options = this.optionStudent;
        } else {
          this.classes.multiple = true;
          this.options = this.optionTeacher;
        }
      } else {
        this.message.error('token已过期，请重新登陆');
      }
    },
    async getClasses() {
      this.changeRow.changeClasses = !this.changeRow.changeClasses;
      if (this.changeRow.changeClasses) {
        const data = await getClasses();
        this.classes.data = data;
      }
    },
    async updateUser() {
      this.changeRow.changeClasses = this.changeRow.changeName = this.changeRow.changePassword = this.changeRow.changeSex = false
      let classes!: string[] | string;
      let name!: string;
      let sex!: number;
      if (this.changeInfoForm.classes.length > 0) {
        classes = this.changeInfoForm.classes;
      }
      if (this.changeInfoForm.name.length > 0) {
        name = this.changeInfoForm.name;
      }
      if ((this.changeInfoForm.sex == 1 && this.user.sex == '女') || (this.changeInfoForm.sex == 0 && this.user.sex == '男')) {
        sex = this.changeInfoForm.sex
      }
      if (await updateUser(this.user.account, name, sex) == 0) {
        this.setSelfData();
        this.message.success('已成功修改个人数据');
      } else {
        this.message.error('修改个人信息失败');
      }
      if (this.changeInfoForm.classes.length) {
        await linkClass(this.user.account, this.changeInfoForm.classes);
        this.setSelfData();
        this.message.success('已成功修改个人数据');
      }
    }
  }
})
</script>